package com.novel.base.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.novel.authorization.staff.entity.NfUser;
import com.novel.authorization.staff.vo.UserInfoVO;
import com.novel.base.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * FieldObjectHandler
 * 通用字段处理器
 *
 * @author 樊温军
 * @date 2025/3/23 上午8:59
 */

@Slf4j
@Component
public class FieldObjectHandler implements MetaObjectHandler {

    private static final String CREATE_TIME = "createTime";
    private static final String CREATE_BY = "createBy";
    private static final String CREATE_BY_NAME = "createByName";
    private static final String UPDATE_TIME = "updateTime";
    private static final String UPDATED_BY = "updateBy";
    private static final String UPDATED_BY_NAME = "updateByName";

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        LocalDateTime currentDate = LocalDateTime.now();
        this.setFieldValByName(CREATE_TIME, currentDate, metaObject);
        this.setFieldValByName(UPDATE_TIME, currentDate, metaObject);
        if (StpUtil.isLogin()) {
            UserInfoVO userInfoVO = (UserInfoVO) StpUtil.getSession().get(CommonConstants.USER_SESSION_KEY);
            if (userInfoVO != null) {
                NfUser user = userInfoVO.getUser();
                if (user != null) {
                    this.setFieldValByName(CREATE_BY_NAME, user.getUname(), metaObject);
                    this.setFieldValByName(UPDATED_BY_NAME, user.getUname(), metaObject);
                }
            }
            this.setFieldValByName(CREATE_BY, StpUtil.getLoginIdAsLong(), metaObject);
            this.setFieldValByName(UPDATED_BY, StpUtil.getLoginIdAsLong(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
        if (StpUtil.isLogin()) {
            UserInfoVO userInfoVO = (UserInfoVO) StpUtil.getSession().get(CommonConstants.USER_SESSION_KEY);
            if (userInfoVO != null) {
                NfUser user = userInfoVO.getUser();
                if (user != null) {
                    this.setFieldValByName(UPDATED_BY_NAME, user.getUname(), metaObject);
                }
            }
            this.setFieldValByName(UPDATED_BY, StpUtil.getLoginIdAsLong(), metaObject);
        }
    }

}
